﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using haptic.src.engine.sprite;
using haptic.src.engine.render;
using Microsoft.Xna.Framework;
using haptic.src.engine.core;

namespace haptic.src.engine.scene
{
    [Serializable]
    public class SpriteNode : Node, IDrawable2
    {
        #region Constructors
        public SpriteNode()
        {
            m_eType = NodeType.E_SPRITE;
        }
        public SpriteNode(ISprite oSprite)
        {
            m_oSprite = oSprite;
            m_eType = NodeType.E_SPRITE;
        }
        #endregion

        #region Load
        public override Result Load()
        {
            if (m_oSprite != null)
                return m_oSprite.Load();
            else
                return Result.Success;
        }
        public override void Unload()
        {
            if (m_oSprite != null)
                m_oSprite.Unload();
        }
        #endregion

        #region Update
        public override void Update(GameTime oTime)
        {
            base.Update(oTime);
            m_oSprite.Update(oTime);
        }
        #endregion

        #region Draw
        public override void Draw(Renderer oRenderer)
        {
            m_oSprite.Draw(oRenderer, mWorld.O, 0.0f);
        }
        #endregion

        #region Serialization
        public XmlSchema GetSchema()
        {
            return null;
        }
        public void WriteXml(XmlWriter w)
        {
            XmlSerializerNamespaces oNs = new XmlSerializerNamespaces();
            oNs.Add("", "");

            // sprite
            if (m_oSprite != null)
            {
                w.WriteStartElement("sprite");
                w.WriteAttributeString("type", m_oSprite.GetType().ToString());
                XmlSerializer oSrlz = new XmlSerializer(m_oSprite.GetType());
                oSrlz.Serialize(w, m_oSprite, oNs);
                w.WriteEndElement();
            }
        }
        public void ReadXml(XmlReader r)
        {
            if (r.ReadToFollowing("sprite"))
            {
                Type oType = Type.GetType(r.GetAttribute("type"));
                XmlSerializer oSrlz = new XmlSerializer(oType);
                r.ReadToDescendant(oType.Name);
                m_oSprite = (ISprite)oSrlz.Deserialize(r);
            }
        }
        #endregion

        #region Attributes
        [XmlIgnore]
        public ISprite m_oSprite;
        #endregion
    }
}
